package com.crm.system.service.impl.trainingManager;

import com.alibaba.fastjson.JSONObject;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.Enum.ContractStatusEnum;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.customerManager.CustomerContactPerson;
import com.crm.model.entity.internalTrainingManager.NxContact;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.entity.trainingManager.TrainingContact;
import com.crm.model.entity.trainingManager.TrainingContract;
import com.crm.model.entity.trainingManager.TrainingOrderProduct;
import com.crm.model.qo.trainingManager.TrainContractAddQO;
import com.crm.model.qo.trainingManager.TrainingContactListQO;
import com.crm.model.vo.trainingManager.TrainingContractDetailVO;
import com.crm.model.vo.trainingManager.TrainingContractVO;
import com.crm.service.csd.customerManager.CustomerDbService;
import com.crm.service.customerManager.CustomerPoolDbService;
import com.crm.service.internalTrainingManager.CustomerUserDbService;
import com.crm.service.internalTrainingManager.NxContactDbService;
import com.crm.service.trainingManager.TrainingContractDbService;
import com.crm.service.trainingManager.TrainingOrderProductDbService;
import com.crm.system.service.customerManager.CustomerPoolService;
import com.crm.system.service.trainingManager.TrainingContractService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author luojie
 * @date 2021/9/13 16:04
 */
@Service
public class TrainingContractServiceImpl implements TrainingContractService {

    @Autowired
    private TrainingContractDbService trainingContractDbService;
    @Autowired
    private TrainingOrderProductDbService trainingOrderProductDbService;
    @Autowired
    private CustomerUserDbService customerUserDbService;
    @Autowired
    private NxContactDbService nxContactDbService;
    @Autowired
    CustomerPoolDbService customerPoolDbService;

    /***
     * @Description:添加内训合同
     * @Param: trainContractAddQO 内训合同对象
     * @Author: luojie
     * @Date: 2021/9/13 16:06
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Boolean addTrainingContract(TrainContractAddQO trainContractAddQO) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String contractId = CommonUtils.getGUID();
        String orderId = CommonUtils.getGUID();
        TrainingContract trainingContract = new TrainingContract();
        trainingContract.setTrainingContractId(contractId);
        trainingContract.setContractNumber("C"+ new Date().getTime());
        trainingContract.setContractStatus(ContractStatusEnum.NOT_EFFECT.getContractStatus());
        trainingContract.setCustomerId(trainContractAddQO.getCustomerId());
        trainingContract.setCustomerName(trainContractAddQO.getCustomerName());
        trainingContract.setContactId(trainContractAddQO.getContactId());
        trainingContract.setContactName(trainContractAddQO.getContactName());
        trainingContract.setContactDetails(trainContractAddQO.getContactDetails());
        trainingContract.setCustomerEmail(trainContractAddQO.getCustomerEmail());
        trainingContract.setContractStartDate(trainContractAddQO.getContractStartDate());
        trainingContract.setContractEndDate(trainContractAddQO.getContractEndDate());
        trainingContract.setContractAnnexId(trainContractAddQO.getContractAnnexId());
        trainingContract.setContractNotes(trainContractAddQO.getContractNotes());
        trainingContract.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        trainingContract.setContractReceivables(trainContractAddQO.getContractReceivables());
        trainingContract.setCreatePeopleId(userAccount.getAccountId());
        trainingContract.setCreateTm(new Date());
        trainingContract.setUpdatePeopleId(userAccount.getAccountId());
        trainingContract.setUpdateTm(new Date());
        //回款状态回款状态：0-未回款；1-已回款；3-部分回款
        trainingContract.setPaymentStatus("0");
        //提成发放状态--1:已全部发放；2:部分发放;3:未发放
        trainingContract.setCommissionStatus("3");
        trainingContract.setOrderId(orderId);
        trainingContract.setOrderNumber("D" + new Date().getTime());
        trainingContract.setRefundStatus(1);
        trainingContract.setCompanyId(userAccount.getCompanyId());
        trainingContract.setTrainingId(trainContractAddQO.getTrainingId());
        Boolean result = trainingContractDbService.insertTrainingContract(trainingContract);

        //插入合同产品
        List<JSONObject> productList = trainContractAddQO.getProductList();
        for (JSONObject product : productList) {
            TrainingOrderProduct trainingOrderProduct = new TrainingOrderProduct();
            trainingOrderProduct.setProductId(CommonUtils.getGUID());
            trainingOrderProduct.setProductName(product.getString("productName"));
            trainingOrderProduct.setProductPrice(product.getBigDecimal("productPrice"));
            trainingOrderProduct.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());
            trainingOrderProduct.setOrderId(orderId);
            trainingOrderProduct.setContractId(contractId);
            trainingContract.setCreatePeopleId(userAccount.getAccountId());
            trainingContract.setCreateTm(new Date());
            trainingContract.setUpdatePeopleId(userAccount.getAccountId());
            trainingContract.setUpdateTm(new Date());
            trainingOrderProductDbService.insertTrainingOrderProduct(trainingOrderProduct);
        }
        return true;
    }

    /***
     * @Description:查询内训客户列表
     * @Param:
     * @Author: luojie
     * @Date: 2021/9/14 14:06
     */
    @Override
    public List<JSONObject> getTrainingCustomerList() {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        List<JSONObject> jsonObjects = customerUserDbService.selectCustomerByOwnerId(userAccount.getAccountId());
        return jsonObjects;
    }

    /***
     * @Description:根据客户id获取内训客户联系人
     * @Param:customerId 客户id
     * @Author: luojie
     * @Date: 2021/9/14 15:30
     */
    @Override
    public List<JSONObject> getTrainingCustomerContactList(String customerId) {
        List<JSONObject> result = new ArrayList<JSONObject>();
        //查内训下客户联系人
        List<NxContact> nxContactList = nxContactDbService.selectNxContactByCustomerId(customerId);
        nxContactList.stream().forEach(nxContact -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("contactId",nxContact.getContactId());
            jsonObject.put("contactName",nxContact.getContactName());
            jsonObject.put("contactInformation",nxContact.getContactInformation());
            result.add(jsonObject);
        });

        //查普通的客户下联系人
        List<CustomerContactPerson> customerContactPersonList = customerPoolDbService.selectContactPersonListByCustomerId(customerId);
        customerContactPersonList.stream().forEach(customerContactPerson -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("contactId",customerContactPerson.getCustomerContactPersonId());
            jsonObject.put("contactName",customerContactPerson.getContactName());
            jsonObject.put("contactInformation",customerContactPerson.getContactInformation());
            result.add(jsonObject);
        });
        return result;
    }

    /**
     * (用户模块)内训管理-内训合同列表
     * @param trainingContactListQO --查询条件
     * @param pageIndex/pageSize    --页码/分页大小
     * @param sortName/sortOrder    --排序字段/排序规则(ASC/DESC)
     * @return
     */
    @Override
    public DhPageInfo<TrainingContractVO> selectTrainingContractVOList(TrainingContactListQO trainingContactListQO,Integer pageIndex,Integer pageSize,String sortName,String sortOrder) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        //排序
        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "createTm": {
                    order.append("t.create_tm ").append(sortOrder);//创建时间
                }
                break;
                default:
                    break;
            }
        }

        List<TrainingContractVO> trainingContractVOList = trainingContractDbService.selectTrainingContractVOList(trainingContactListQO,order.toString());
        PageInfo<TrainingContractVO> pageInfo =  new PageInfo(trainingContractVOList);
        return new DhPageInfo<TrainingContractVO>(pageInfo, trainingContractVOList);
    }

    /**
     * (用户模块)内训管理-》内训合同列表-》合同详情-》合同信息
     * @param trainingContractId --内训合同ID
     * @author yincuimei
     * @return
     */
    @Override
    public TrainingContractDetailVO selectTrainingContractDetailVO(String trainingContractId) {
        if(!StringUtils.isBlank(trainingContractId)){
            return trainingContractDbService.selectTrainingContractDetailVO(trainingContractId);
        }
        return null;
    }

    /**
     * 内训线索池列表(管理)/内训线索(用户)内训详情--合同订单列表
     * @param trainingId  --内训ID
     * @return
     */
    @Override
    public DhPageInfo<TrainingContractVO> selectTrainingContractListByTrainingId(String trainingId, Integer pageIndex, Integer pageSize, String sortName, String sortOrder) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        //排序
        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "createTm": {
                    order.append("t.create_tm ").append(sortOrder);//创建时间
                }
                break;
                default:
                    break;
            }
        }
        List<TrainingContractVO> trainingContractVOList = trainingContractDbService.selectTrainingContractListByTrainingId(trainingId,order.toString());
        PageInfo<TrainingContractVO> pageInfo =  new PageInfo(trainingContractVOList);
        return new DhPageInfo<TrainingContractVO>(pageInfo, trainingContractVOList);
    }

    /**
     * 通过客户id查询内训联系人
     * @author baijian
     * @return
     */
    @Override
    public DhPageInfo<NxContact> selectContactByCustomerId(String customerId, Integer pageIndex, Integer pageSize, String sortName, String sortOrder) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        List<NxContact> trainingContractVOList = nxContactDbService.selectNxContactByCustomerId(customerId);
        PageInfo<NxContact> pageInfo =  new PageInfo(trainingContractVOList);
        return new DhPageInfo<NxContact>(pageInfo, trainingContractVOList);
    }
}
